package com.example.demo.controller;

import com.example.demo.Entity.MathCaptchaRequest;
import com.example.demo.Entity.User;
import com.example.demo.Service.MathCaptchaService;
import com.example.demo.Service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.demo.Entity.Work;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MathCaptchaService mathCaptchaService;

    /**
     * 用户登录接口。
     *
     * @param params 包含用户名、密码和验证码ID及用户输入的答案。
     * @return 登录结果。
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> params) {
        // 获取参数
        String username = params.get("username");
        String password = params.get("password");
        String captchaId = params.get("captchaId");
        String userInputStr = params.get("userInputStr");

        System.out.println("Received parameters - 用户名: " + username +
                ", 密码: " + password +
                ", 验证码ID: " + captchaId +
                ", 用户输入: " + userInputStr);

        if (username == null || password == null || captchaId == null || userInputStr == null) {
            return ResponseEntity.badRequest().body(Collections.singletonMap("success", false));
        }

        try {
            int userInput = Integer.parseInt(userInputStr);

            // 验证数学问题验证码
            boolean isCaptchaValid = mathCaptchaService.validateAnswer(captchaId, userInput);
            if (!isCaptchaValid) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Collections.singletonMap("message", "验证码错误"));
            }

            // 检查用户名和密码是否匹配
            User user = userService.findByUsernameAndPassword(username, password);

            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Collections.singletonMap("message", "用户名或密码错误"));
            }

            // 登录成功，构建响应体
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("userId", user.getId()); // 添加用户ID到响应体

            return ResponseEntity.ok(response);
        } catch (NumberFormatException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Collections.singletonMap("message", "无效的验证码输入"));
        }
    }
    /**
     * 获取新的数学问题验证码。
     *
     * @return 新的数学问题及唯一标识符。
     */
    @GetMapping("/getMathCaptcha")
    public ResponseEntity<MathCaptchaService.MathCaptchaResponse> getMathCaptcha() {
        System.out.println(mathCaptchaService.generateMathProblem());
        System.out.println(mathCaptchaService.generateMathProblem().getCaptchaId());
        return ResponseEntity.ok(mathCaptchaService.generateMathProblem());
    }

    @GetMapping("/{userId}")
    public User getUserInfo(@PathVariable Long userId) {
        return userService.getUserInfo(userId);
    }

    @GetMapping("/{userId}/works")
    public ResponseEntity<List<Work>> getUserWorks(@PathVariable Long userId) {
        List<Work> works = userService.getUserWorks(userId);
        return new ResponseEntity<>(works, HttpStatus.OK);
    }

    @GetMapping("/{userId}/likes/image-urls")
    public ResponseEntity<List<String>> getUserLikedImageUrls(@PathVariable Long userId) {
        List<String> imageUrls = userService.getUserLikedImageUrls(userId);
        return new ResponseEntity<>(imageUrls, org.springframework.http.HttpStatus.OK);
    }
    /**
     * 验证用户提供的答案（可选，前端可以直接在登录时验证）。
     *
     * @param request 包含验证码ID和用户输入的答案的对象。
     * @return 验证结果。
     */
    @PostMapping(value = "/validateMathCaptcha")
    public ResponseEntity<Map<String, Object>> validateMathCaptcha(@RequestBody MathCaptchaRequest request) {
        System.out.println("Captcha ID: " + request.getCaptchaId() + ", User Input: " + request.getUserInput());
        boolean isValid = mathCaptchaService.validateAnswer(request.getCaptchaId(), request.getUserInput());
        return ResponseEntity.ok(Collections.singletonMap("success", isValid));
    }

    @GetMapping("/test")
    public ResponseEntity<Map<String, String>> test() {
        Map<String, String> response = new HashMap<>();
        response.put("message", "Hello, Jackson!");
        return ResponseEntity.ok(response);
    }
    @PutMapping("/{userId}")
    public ResponseEntity<User> updateUserInfo(@PathVariable Long userId, @RequestBody User updatedUser) {
        try {
            User updated = userService.updateUser(userId, updatedUser);
            return ResponseEntity.ok(updated);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
}